package com.smileus.common;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.smileus.util.EnvProperties;

/**
 * FileName：Env.java Date�?2010-12-6 User: heng.dong
 * Alipay
 */
@SuppressWarnings("unchecked")
public class Env {
	static final String separator = File.separator;
	private static ApplicationContext applicationContext;//
	// 用来存储业务处理上下文过程中的消息提示
	private static final ThreadLocal<List<String>> message = new ThreadLocal<List<String>>();

	public static void putMessage(String busMsg) {
		if (message.get() == null) {
			message.set(new ArrayList<String>());
		}
		message.get().add(busMsg);
	}

	/**
	 * 返回的message之间以分好隔开，此消息之后还可以继续获取，
	 * 
	 * 最后一次后去请调用getAndRemoveMessage()方法
	 * @return
	 */
	public static String getMessage(){
		if (message.get() == null || message.get().size() == 0) {
			return null;
		}
		StringBuilder sBuilder = new StringBuilder();
		for (String msg : message.get()) {
			sBuilder.append(msg).append(";");
		}
		return sBuilder.toString();
	}
	
	/**
	 * 取得消息之后，移除ThreadLocal中的消息，适合最后一次获取消息用
	 * @return
	 */
	public static String  getAndRemoveMessage(){
		String result = getMessage();
		message.remove();//将消息移除，否则会长期占据内存.
		return result;
	}
	/**
	 * getApplicationContext
	 * 
	 * @param Env
	 * @return ApplicationContext
	 */
	public static ApplicationContext getApplicationContext() {
		if (applicationContext == null) {
			applicationContext = new ClassPathXmlApplicationContext(EnvProperties.getProperty("ContextName"));
		}
		return applicationContext;
	}

	public static void setApplicationContext(ApplicationContext appContext) {
		applicationContext = appContext;
	}

	/**
	 * 根据bean id获取bean
	 * 
	 * @param name
	 * @return
	 */
	public static Object getBean(String name) {
		return getApplicationContext().getBean(name);
	}

	/**
	 * 根据bean id获取指定类型的bean
	 * 
	 * @param name
	 * @return
	 */

	public static <T> T getBean(String name, Class<T> clazz) {
		return (T) getBean(name);
	}

	public static boolean containsBean(String name) {
		return getApplicationContext().containsBean(name);
	}

	public static Object getConfigValue(String key) {
		return Env.getBean("systemConfig", Map.class).get(key);
	}

	public static <T> T getConfigValue(String key, Class<T> clazz) {
		return (T) Env.getBean("systemConfig", Map.class).get(key);
	}
}
